import { CloseCircleOutlined } from '@ant-design/icons';
import { Button, Card, Col, Form, Input, Popover, Row, Select } from 'antd';
import React, { FC, useState, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import { connect, Dispatch } from 'umi';
import MDEditor from '@/components/MDEditor/index.tsx'
import styles from './style.less';
import { getPageQuery, isEmpty } from '@/utils/utils';
import { DictState, DictType } from '@/models/dict'

import { getMachine } from "@/services/machine"
import { history } from 'umi';


type InternalNamePath = (string | number)[];

const { Option } = Select;

const fieldLabels = {
  system: '业务系统',
  use: '用途',
  ip: 'IP',
  port: '端口',
  os: '操作系统',
  osversion: '版本',
  username: '用户',
  password: '密码',
  username1: '普通用户',
  password1: '密码',
  owner: '负责人',
  env: '环境'
};


interface AdvancedFormProps {
  dispatch: Dispatch<any>;
  submitting: boolean;
  osDict: DictType[];
  systemDict: DictType[];
  ownerDict: DictType[];
  envDict: DictType[];
}

interface ErrorField {
  name: InternalNamePath;
  errors: string[];
}

const AdvancedForm: FC<AdvancedFormProps> = ({ submitting, dispatch, osDict, systemDict, ownerDict, envDict }) => {
  const [form] = Form.useForm();
  const [error, setError] = useState<ErrorField[]>([]);
  const [deploy, setDeploy] = useState<string>('');

  useEffect(() => {
    dispatch({
      type: 'dict/init',
      payload: {},
    });
    form.setFieldsValue({ deploy: '',port:22 })
  }, [])
  const getErrorInfo = (errors: ErrorField[]) => {
    const errorCount = errors.filter((item) => item.errors.length > 0).length;
    if (!errors || errorCount === 0) {
      return null;
    }
    const scrollToField = (fieldKey: string) => {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
      if (labelNode) {
        labelNode.scrollIntoView(true);
      }
    };
    const errorList = errors.map((err) => {
      if (!err || err.errors.length === 0) {
        return null;
      }
      const key = err.name[0] as string;
      return (
        <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
          <CloseCircleOutlined className={styles.errorIcon} />
          <div className={styles.errorMessage}>{err.errors[0]}</div>
          <div className={styles.errorField}>{fieldLabels[key]}</div>
        </li>
      );
    });
    return (
      <span className={styles.errorIcon}>
        <Popover
          title="表单校验信息"
          content={errorList}
          overlayClassName={styles.errorPopover}
          trigger="click"
          getPopupContainer={(trigger: HTMLElement) => {
            if (trigger && trigger.parentNode) {
              return trigger.parentNode as HTMLElement;
            }
            return trigger;
          }}
        >
          <CloseCircleOutlined />
        </Popover>
        {errorCount}
      </span>
    );
  };

  const onFinish = (values: { [key: string]: any }) => {
    setError([]);
    const query = getPageQuery()
    let ID: any = query.ID || 0
    const copy: any = query.copy || 0
    if (copy > 0) {
      ID = 0;
    }
    values.deploy = values.deploy ?? deploy
    if (isEmpty(values.deploy)) {
      alert("脚本为空，请填写！");
      return;
    }
    dispatch({
      type: 'machine/saveMachine',
      payload: { ...values, ...{ id: ID } },
    });
    history.replace({
      pathname: '/machine/list'
    });
  };

  const onFinishFailed = (errorInfo: any) => {
    setError(errorInfo.errorFields);
  };

  const onGetMachine = (vditor: any) => {
    const query = getPageQuery()
    const ID: any = query.ID || 0

    if (ID > 0) {
      getMachine({ id: ID }).then(res => {
        if (res.code == 0 && res.results.length > 0) {
          const row = res.results[0]
          const deploy = row.deploy
          delete row['deploy']
          form.setFieldsValue(row)
          vditor.setValue(deploy)
          setDeploy(deploy)
        }
      })
    } else {
      form.setFieldsValue({ deploy: `` })
    }
  }



  return (
    <Form
      form={form}
      layout="vertical"
      hideRequiredMark
      // initialValues={{ members: tableData }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
    >
      <PageContainer >
        <Card title="" className={styles.card} bordered={false}>
          <Row gutter={16}>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <Form.Item
                label={fieldLabels.ip}
                name="ip"
                rules={[{ required: true, message: '请输入ip' }]}
              >
                <Input
                  style={{ width: '100%' }}
                  placeholder="请输入ip"
                />
              </Form.Item>
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <Form.Item
                label={fieldLabels.port}
                name="port"
                rules={[{ required: true, message: '请输入端口' }]}
              >
                <Input
                  style={{ width: '100%' }}
                  placeholder="请输入端口"
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <Form.Item
                label={fieldLabels.system}
                name="system"
                rules={[{ required: true, message: '请选择业务系统' }]}
              >
                <Select placeholder="请选择业务系统">
                  {
                    systemDict.map((o: DictType, index) =>
                      <Option key={index} value={o.value}>{o.label}</Option>
                    )
                  }
                </Select>
              </Form.Item>
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <Form.Item
                label={fieldLabels.use}
                name="use"
                rules={[{ required: true, message: '请输入用途' }]}
              >
                <Input
                  style={{ width: '100%' }}
                  placeholder="请输入用途"
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <Form.Item
                label={fieldLabels.os}
                name="os"
                rules={[{ required: true, message: '请选择操作系统' }]}
              >
                <Select placeholder="请选择操作系统">
                  {
                    osDict.map((o: DictType, index) =>
                      <Option key={index} value={o.value}>{o.label}</Option>
                    )
                  }
                </Select>
              </Form.Item>
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <Form.Item
                label={fieldLabels.osversion}
                name="osversion"
                rules={[{ required: false, message: '请输入系统版本' }]}
              >
                <Input
                  style={{ width: '100%' }}
                  placeholder="请输入系统版本"
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <Form.Item
                label={fieldLabels.username}
                name="username"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input
                  style={{ width: '100%' }}
                  placeholder="请输入用户名"
                />
              </Form.Item>
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <Form.Item
                label={fieldLabels.password}
                name="password"
                rules={[{ required: true, message: '请输入密码' }]}
              >
                <Input.Password
                  style={{ width: '100%' }}
                  placeholder="请输入密码"
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <Form.Item
                label={fieldLabels.owner}
                name="owner"
                rules={[{ required: false, message: '请选择负责人' }]}
              >
                <Select placeholder="请选择负责人">
                  {
                    ownerDict.map((o: DictType, index) =>
                      <Option key={index} value={o.value}>{o.label}</Option>
                    )
                  }
                </Select>
              </Form.Item>
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <Form.Item
                label={fieldLabels.env}
                name="env"
                rules={[{ required: false, message: '请选择环境' }]}
              >
                <Select placeholder="请选择环境">
                  {
                    envDict.map((o: DictType, index) =>
                      <Option key={index} value={o.value}>{o.label}</Option>
                    )
                  }
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="deploy">
            <MDEditor onAfter={onGetMachine} />
            {/* <MDEditor   /> */}
          </Form.Item>
        </Card>


      </PageContainer>
      <FooterToolbar>
        {getErrorInfo(error)}
        <Button type="primary" onClick={() => form?.submit()} loading={submitting}>
          提交
        </Button>
      </FooterToolbar>
    </Form>
  );
};

export default connect(({ loading, dict }: { loading: { effects: { [key: string]: boolean } }, dict: DictState }) => ({
  submitting: loading.effects['machine/saveMachine'],
  osDict: (dict.dictlist || []).filter(o => o.type == 'os').sort((prev, next) => {
    return prev['sort'] - next['sort']
  }),
  systemDict: (dict.dictlist || []).filter(o => o.type == 'system').sort((prev, next) => {
    return prev['sort'] - next['sort']
  }),
  ownerDict: (dict.dictlist || []).filter(o => o.type == 'owner').sort((prev, next) => {
    return prev['sort'] - next['sort']
  }),
  envDict: (dict.dictlist || []).filter(o => o.type == 'env').sort((prev, next) => {
    return prev['sort'] - next['sort']
  }),
}))(AdvancedForm);
